package com.sj.security;

import cn.hutool.json.JSONUtil;
import com.sj.common.lang.ApiResultMsg;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021-08-02
 * Time: 下午 12:00
 * Description: security登陆失败配置
 *
 * @author xiaoqi
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");

        ServletOutputStream outputStream = response.getOutputStream();
        if (e instanceof BadCredentialsException) {
            outputStream.write(JSONUtil.toJsonStr(ApiResultMsg.error("密码错误")).getBytes("UTF-8"));
        } else {
            outputStream.write(JSONUtil.toJsonStr(ApiResultMsg.error(e.getMessage())).getBytes("UTF-8"));
        }
        outputStream.flush();
        outputStream.close();
    }
}